package com.wing.factory.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wing.common.utils.HttpClientaSsist;
import com.wing.common.utils.HttpHelper;
import com.wing.company.dao.CompanyInfoDto;
import com.wing.factory.dao.FacFactoryDao;
import com.wing.factory.model.entity.FacFactory;
import com.wing.factory.model.request.FacFactoryForm;
import com.wing.factory.model.response.FacFactoryVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.HttpHead;
import org.json.JSONObject;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static java.lang.System.out;

/**
 * 厂家表-ServiceImpl
 *
 * @author
 */
@Service
@Slf4j
public class FacFactoryServiceImpl extends ServiceImpl<FacFactoryDao, FacFactory> implements FacFactoryService {

    private static final String appkey = "0969963c8ca54046951aa74fd387a9ce";
    private static final String secretKey = "FDBD8F8C0989F84FC7D67CE57D69516C";

    @Override
    public int add(FacFactoryForm facFactoryForm) {

        //校验

        FacFactory facFactory =new FacFactory();
        CopyOptions copyOptions = CopyOptions.create()
        .setEditable(FacFactory.class)
        .setIgnoreError(true)
        .setIgnoreNullValue(true);
        BeanUtil.copyProperties(facFactoryForm, facFactory, copyOptions);

        return baseMapper.insert(facFactory);
    }

    @Override
    public List<FacFactoryVO> list4app(Map<String, Object> params) {
        return baseMapper.list4app(params);
    }

    @Override
    public Page<FacFactoryVO> pageList4app(Page page, Map<String, Object> params) {
        List<FacFactoryVO> list = baseMapper.list4app(page, params);
        page.setRecords(list);
        return page;
    }

    @Override
    public FacFactoryVO get4appById(Long id) {
        return baseMapper.get4appById(id);
    }

    /**
     * 每次查询新的厂家都同步一次查询出来的厂家数据,存在就修改 不存在就新增
     * @param searchKey
     */
    @Override
    public FacFactory getQccEnterpricceInfo(String searchKey) {
        //访问企业数据
        List<CompanyInfoDto> companyList = getCompanyInfo(searchKey);
        if (companyList.size() > 0) {
            for (CompanyInfoDto companyInfo : companyList) {
                FacFactory facFactory = new FacFactory();
                facFactory.setFactoryName(companyInfo.getName())
                        .setFactoryContact(companyInfo.getOperName())
                        .setFactoryAddress(companyInfo.getAddress());
                Map<String,Object> map = new HashMap<>();
                map.put("enterpricce_name",facFactory.getFactoryName());
                if(baseMapper.list4app(map).size() > 0){
                    baseMapper.updateById(facFactory);
                    return facFactory;
                }else{
                    baseMapper.insert(facFactory);
                    return facFactory;

                }
            }
        }
        return null;

    }

    /**
     * 通过企查查获取企业信息
     *
     * @param searchKey
     * @return
     */
    public List<CompanyInfoDto> getCompanyInfo(String searchKey) {
        String reqInterNme = "http://api.qichacha.com/FuzzySearch/GetList";
        String paramStr = "searchkey=".concat(searchKey);
        try {
            HttpHead reqHeader = new HttpHead();
            String[] autherHeader = HttpClientaSsist.RandomAuthentHeader(appkey, searchKey);
            reqHeader.setHeader("Token", autherHeader[0]);
            reqHeader.setHeader("Timespan", autherHeader[1]);
            final String reqUri = reqInterNme.concat("?key=").concat(appkey).concat("&").concat(paramStr);
            String tokenJson = HttpHelper.httpGet(reqUri, reqHeader.getAllHeaders());
            out.println(String.format("==========================>this is response:{%s}", tokenJson));
            JSONObject jsonObject = new JSONObject(tokenJson);
            if ("200".equals(jsonObject.get("Status"))) {
                String result = jsonObject.getString("Result");
                List<CompanyInfoDto> companyInfoDtoList = JSON.parseArray(result, CompanyInfoDto.class);
                if (companyInfoDtoList.size() > 0) {
                    log.info("解析成功:" + companyInfoDtoList.toString());
                    return companyInfoDtoList;

                }
            }

        } catch (Exception e1) {
            e1.printStackTrace();
        }

        return null;
    }

}
